package com.xinan.system.common;

import com.jfinal.aop.Before;
import com.jfinal.core.BaseController;
import com.jfinal.core.Controller;
import com.jfinal.kit.StringKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheInterceptor;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.ehcache.CacheName;
import com.jfinal.plugin.ehcache.IDataLoader;
import com.xinan.utils.Assert;
import com.xinan.utils.Constants;

import java.util.ArrayList;
import java.util.List;


/**
 * CommonController
 */
public class CommonController extends BaseController {
    /**
     * 根据配置的表名和字段信息，查询出对应的列表，显示到grid中
     * 由于where条件含有特殊字符，可以跟在服务路径后面
     */
    private List<?> data;

    public void combgrid() {
        String fields = getPara("fields");
        String table = getPara("table");
        String where = getPara(0);
        Assert.hasText(fields, "fields字段信息不能为空");
        Assert.hasText(table, "table表名不能为空");
        String strWhere = StringKit.notBlank(where) ? " where " + where : "";
        List<Record> combgrid = Db.find("select " + fields + " from " + table + strWhere);
        renderJson(combgrid);
    }

    /**
     * 根据配置的表名和字段信息，查询出来对应的数据，显示在combox中
     */
    public void comb() {
        String fields = getPara("fields");
        String table = getPara("table");
        String where = getPara(0);
        Assert.hasText(fields, "fields字段信息不能为空");
        Assert.hasText(table, "table表名不能为空");
        String strWhere = StringKit.notBlank(where) ? " where " + where : "";
        List<Record> comb = Db.find("select " + fields + " from " + table + strWhere);
        renderJson(comb);
    }

    /**
     * 根据配置的表名和字段信息，查询出对应的列表，显示到grid中
     */
    public void combgridpage() {
        String fields = getPara("fields");
        String table = getPara("table");
        int pageNumber = getParaToInt("page");
        int pageSize = getParaToInt("rows");
        String where = getPara(0);
        Assert.hasText(fields, "fields字段信息不能为空");
        Assert.hasText(table, "table表名不能为空");
        String strWhere = StringKit.notBlank(where) ? " where " + where : "";
        Page<Record> combgrid = Db.paginate(pageNumber, pageSize, "select " + fields, " from " + table + strWhere);
        renderJson(combgrid);
    }

    /**
     * 通用下拉树组件,通过配置表名、字段列表、父字段、开始节点号以及where查询条件
     */
    public void comboTree() {
        String where = getPara(0);

        String fields = getPara("fields");
        String table = getPara("table");
        String pid = getPara("pid");
        String pidStart = getPara("pidStart");
        String id = getPara("id");
        Assert.hasText(fields, "fields字段信息不能为空");
        Assert.hasText(table, "table表名不能为空");
        Assert.hasText(pid, "pid字段信息不能为空");
        Assert.hasText(id, "id字段信息不能为空");
        if (!fields.contains(pid)) {
            fields += "," + pid;
        }
        String strWhere = StringKit.notBlank(where) ? " where " + where + " order by " + pid : "";
        List<Record> _list = Db.find("select distinct " + fields + " from " + table + strWhere);
        List<Record> combList = getComboTree(_list, pid, pidStart, id);
        Record root = new Record();
        root.set("id", 0);
        root.set("text", "请选择");
        combList.add(0,root);
        renderJson(combList);
    }

    /**
     * 递归循环，根据上下级关系生成对应的树组件
     *
     * @param _list
     * @param pid
     * @param pidStart
     * @param id
     * @return
     */
    private List<Record> getComboTree(List<Record> _list, String pid, Object pidStart, String id) {
        List<Record> retList = new ArrayList<Record>();
        for (Record r : _list) {
            Object sPid = r.get(pid);
            if (pidStart.equals(sPid.toString())) {
                if(!r.get(id).equals("0")){
                    List<Record> childMap = getComboTree(_list, pid, r.get(id).toString(), id);
                    if (childMap.size() > 0) {
                        r.set("state", "closed");
                        r.set("children", childMap);
                    }
                }
                retList.add(r);
            }
        }
        return retList;
    }
    
    
    /**
     * 组织机构树获取
     */
    public void orgTree() {
        String where = "";
        // 如果关联文档id不为空则加入查询。
        String  archivesid =getPara("archivesid");
        String  id =getPara("id");

        String fields="";

       if( StringKit.notBlank(archivesid) ==true){
           fields = ",IF ( (select count(*) from oa_archives_org  where orgid=a.id  and archivesid ='"+archivesid+"' ) >0,'true','false' )as  checked";
       }
        if( StringKit.notBlank(id) ==true){
            where = "where a.pid='"+id+"'  " ;
        }

        String strWhere =where+"order by id";
        List<Record>  _list= Db.find("select id,name,pid,pid  as pId,IF ((select count(*)  from auth_org b where a.id=b.pid) >0,'true','false' )as isparent " + fields + "  from auth_org a  "  + strWhere);
        
        renderJson(_list);
    }


    public void orguserTree() {
        String all=getPara("all");
        String orgs="";
        int org = getAttr(Constants.USER_ORG);
        // thisall取当前用户根节点所有用户 or 取上级组织下的所有用户
        if(all.equals("thisallorg")){
             orgs = getPid(org,  data);
        } else {
            orgs =  org+"";
        }
        List<Record>  _list = new ArrayList();
        //  增加CacheKit缓存
        if (all.equals("all")){
            _list=  CacheKit.get("orguserTree", "orguserTree"+all);
            if (_list==null){
                _list= Db.find( "select  c.id ,c.name ,c.ids ,c.pId, nocheck  from(" +
                        "select id,name,pid as ids,pid  as pId,'true' as nocheck   from auth_org a " +
                        "UNION ALL select  Concat(b.username ,'aaa')   as id,  b.cnname as name,b.username as ids  ,b.orgid  as pId,'' as nocheck  from auth_user b " +
                        ") c ");
                CacheKit.put("orguserTree", "orguserTree"+all, _list);
            }
        }  else  {
            _list=  CacheKit.get("orguserTree", "orguserTree"+orgs);
            if (_list==null){
                _list= Db.find( "select  c.id ,c.name ,c.ids ,c.pId," +
                    " nocheck  from( select id,name,pid as ids,pid  as pId,'true' as nocheck   from auth_org a " +
                    "UNION ALL select  Concat(b.username ,'aaa')   as id,  b.cnname as name,b.username as ids  ,b.orgid  as pId,'' as nocheck  from auth_user b   " +
                    ") c where  pId in  (select id from auth_org  where FIND_IN_SET(id, getChildLst('"+orgs+"'))) " +
                    "or id in   (select id from auth_org  where FIND_IN_SET(id, getChildLst('"+orgs+"'))) ");
                   CacheKit.put("orguserTree", "orguserTree"+orgs, _list);
            }
        }
        renderJson(_list);
    }
    /**
     * 获取当前用户所有组织机构
     */
    public void orgChildTree() {
        String where = "";
        String  id =getPara("id");

        String fields="";


        if( StringKit.notBlank(id) ==true){
            where = " where FIND_IN_SET(id, getChildLst("+id+")) " ;
        }

        String strWhere =where+"order by id";
        List<Record>  _list= Db.find("select id,name,pid,pid  as pId,IF ((select count(*)  from auth_org b where a.id=b.pid) >0,'true','false' )as isparent " + fields + "  from auth_org a  "  + strWhere);

        renderJson(_list);
    }
    
    /**
     *返回最根级节点
     */
    public static String getPid(int org,List<?> data){
        // 取的当前机构的最顶节点
//        int org = getAttr(Constants.USER_ORG);
        String id="";
        String pid="";
        String sql="select * from auth_org where  FIND_IN_SET(id,getParentLst("+org+"))  and pid=0 "  ;
        data = Db.find(sql);
        for (int i=0; i<data.size();i++) {
            Object obj = data.get(i);
            Record record = (Record) obj;
            pid=record.get("pid").toString();
            id=record.get("id").toString();
        }
        return id;
    }
}
